package com.zxh.audio;

import com.zxh.util.ThreadPool;
import org.apache.log4j.Logger;

import javax.sound.sampled.*;
import java.io.*;

/**
 * 音频播放
 * 
 * @author zaqzaq 2015年12月11日
 * 
 */
public class PlayUtil {
	private static Logger logger = Logger.getLogger(PlayUtil.class);

	private PlayUtil() {
	}

	// 播音设备
	private static SourceDataLine sd = null;
	// 定义存放录音的字节数组,作为缓冲区
	private static byte bts[] = new byte[10000];

	/**
	 * 播放音频
	 */
	public static synchronized void play(InputStream audioIs) {
		audioIs = new BufferedInputStream(audioIs);
		AudioInputStream ais = null;
		try {
			// 获取音频输入流
			ais = AudioSystem.getAudioInputStream(audioIs);
			// 获取音频编码对象
			AudioFormat audioFormat = ais.getFormat();
			// 打开播音设备
			openSD(audioFormat);
			logger.debug("开始播放音频");
			int cnt;
			// 读取数据到缓存数据
			while ((cnt = ais.read(bts, 0, bts.length)) != -1) {
				if (cnt > 0) {
					// 写入缓存数据
					// 将音频数据写入到混频器
					sd.write(bts, 0, cnt);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭流
				if (ais != null) {
					ais.close();
				}
				if (audioIs != null) {
					audioIs.close();
				}
			} catch (Exception e) {
			}
			sd.close();
		}

		logger.debug("音频播放完毕");
	}
	/**
	 * 用JAVA自带的播放音频
	 * @param audioFile
	 */
	public static void play(File audioFile) throws FileNotFoundException {
		play(new FileInputStream(audioFile));
	}
	

	
	/**
	 * 用mplayer 软件播放音频
	 * @param toFilePath 音频路径
	 */
	public static void playWithMPlayer(final String toFilePath) {
		ThreadPool.execute(new Runnable() {
			public void run() {
				InputStreamReader ir=null;
				Process process=null;
				String commands = "mplayer "+toFilePath;
				try {
					
					logger.info("mplayer开始播放音频:"+commands);
					//一次只播放一个
					synchronized(PlayUtil.class){
						process = Runtime.getRuntime().exec(commands);
					}
					
					logger.info("mplayer结束播放音频:"+commands);
					ir = new InputStreamReader(process.getInputStream());
					BufferedReader input = new BufferedReader(ir);
					String line;
					while ((line = input.readLine()) != null) {
						logger.debug(line);
					}
				} catch (IOException e) {
					logger.error("mplayer播放音频:"+commands+"异常" , e);
				}finally{
					if(null!=ir){
						try {
							ir.close();
						} catch (IOException e) {}
					}
					if(null!=process){
						process.destroy();
					}
				}
			}
		});
		
	}

	// 打开播音设备
	private static void openSD(AudioFormat af) throws LineUnavailableException {
		DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, af);
		sd = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
		sd.open(af);
		sd.start();
	}

}
